<?php
/**
 *
 * This core Bemigo service is intended to make use of the Facebook data about a user
 * and use it to get meaningful recommendations from Hunch API. The service is also responsible
 * for generating display object which will include recommendations and featured items
 * based on the amount of information obtained about the user via Facebook
 * @author mymac80
 *
 */
class Application_Service_Recommend{

	protected $_user;
	protected $_facebook;
	protected $_movies;
	protected $_music;
	protected $_books;

	public function __construct(Entities\Users $user, $facebook){
		if(!empty($user)){
			$this->setUser($user);
		}
		$this->_facebook = $facebook;
	}

	protected function setUser(Entities\Users $user){
		$this->_user = $user;
	}

	public function getUser(){
		return $this->_user;
	}

	public function getMovies($limit = 1){
		$fbMovies = $this->_facebook->getMovies($this->_user->getFacebookId());
		$results = $this->getHunchResults($fbMovies, 'list_movie');
		if(count($results)){
			return array_slice($results, 0, $limit);
		}
		return array();
	}


	protected function getHunchResults($fbResult, $topic_id){
		$reco_arr = array();
		$hunch = new Bemigo_Service_Hunch(Zend_Registry::get("configuration")->hunch->app);
		$hunch_recommendation = new Bemigo_Recommend_Hunch($hunch);
		//Get FB matched results from Hunch

		if(count($fbResult)){
			$fb_result_ids = implode(",", array_keys($fbResult));

			$complete_match_results = $hunch_recommendation->getResults(array(
				'topic_ids' => $topic_id,
				'result_ids' => $fb_result_ids
			));
			$reco_arr = $complete_match_results;
		}

		//Grab all aliases from matched results to block from all future similar results
		if(count($reco_arr)){
			$blocked_ids = "";
			foreach ($reco_arr as $reco){
				if(!empty($reco['aliases'])){
					$blocked_ids .= $reco['aliases'].",";
					break;
				}
			}
			$blocked_ids = trim($blocked_ids,",");
		}

		//Get similar results from Hunch
		if(count($reco_arr)){
			foreach ($reco_arr as $match){
				$similar_results = $hunch_recommendation->getSimilarResults(array(
					'topic_ids' => $topic_id,
					'result_id' => $match['result_id'],
					'blocked_result_ids' => $blocked_ids
				));
				$reco_arr = array_merge($reco_arr, $similar_results);
			}
		}

		//Get featured results from Hunch
		$featured_results = $hunch_recommendation->getResults(array(
			'topic_ids' => $topic_id
		));
		$reco_arr = array_merge($reco_arr, $featured_results);
		return $reco_arr;
	}
}